package cn.cloudtogo.server.atomapi.event;

import cn.cloudtogo.common.atomapi.token.ApiToken;
import cn.cloudtogo.server.atomapi.ApiTokenCreateParam;
import cn.cloudtogo.server.atomapi.GendbApiTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

/**
 * @author yaolianhua789@gmail.com
 **/
@Component
@Slf4j
@EnableAsync
public class ApiTokenEventListener {

    private final GendbApiTokenService apiTokenService;

    public ApiTokenEventListener(GendbApiTokenService apiTokenService) {
        this.apiTokenService = apiTokenService;
    }

    @EventListener
    @Async
    public void globalApiTokenCreated(GlobalApiTokenCreatedEvent event) {
        ApiTokenCreateParam apiTokenCreateParam = event.getApiTokenCreateParam();
        try {
            ApiToken apiToken = apiTokenService.generate(apiTokenCreateParam);
            log.info("[{}] Api token generated for datasource [{}]", apiToken.getNotes(), apiTokenCreateParam.getUuid());
        } catch (Exception e1) {
            log.error("Exception for api-token generate. {}", e1.getMessage(), e1);
        }

    }

    @EventListener
    @Async
    public void apiTokenListDeleted(ApiTokenListDeletedEvent event) {
        String objectId = event.getUuid();

        try {
            apiTokenService.removeAll(objectId);
        } catch (Exception e1) {
            log.error("Exception for api-token list remove. {}", e1.getMessage(), e1);
        }

    }

}
